package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.pojos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements LoginService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查参数  hibernate validated校验
        //2 查询自媒体用户
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getName, dto.getName()));
        //判断用户名是否存在
        if (wmUser==null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //若存在判断用户登录状态
        if (wmUser.getStatus().intValue() != 9) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "用户状态异常，请重新登录");
        }
        //获取登录密码
        //dto.getPassword() + wmUser.getSalt()).getBytes()
        //指：获取的密码+盐转换成byte数组
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        //判断密码是否正确
        if (!dto.getPassword().equals(pwd)) {
            //提示登录密码不正确
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //正确则返回jwt结果，创建Map集合封装
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
        //创建WmUserVO对象
        WmUserVO wmUserVO = new WmUserVO();
        //将wmUser对象的属性值拷贝到wmUserVO
        BeanUtils.copyProperties(wmUser, wmUserVO);
        map.put("user", wmUserVO);
        //返回map
        return ResponseResult.okResult(map);

    }
}
